const express = require('express')
const router = express.Router()
const fs = require('fs')
const path = require('path')
const { host } = require('../../../config')
const multipart = require('../../middleware/content-type/multypart')

router.use(multipart('./server/upload'))

router.post('/upload', async (req, res) => {
    res.send(JSON.stringify({
        code: 200,
        data: req.body
    }))
})

router.delete('/unload', async (req, res) => {
    let result = {
        code: 200,
        rmFile: '',
        msg: ''
    }
    let { paths } = req.body
    let absolutePath = path.join(__dirname, '../../../', paths.replace(host + '/static', '/server'))
    try {
        fs.rmSync(absolutePath)
        result.rmFile = paths
        result.msg = '删除图片成功'
    } catch (err) {
        if (err.toString().includes('is not a function')) {
            result.code = 400
            result.msg = '版本不兼容，请使用node 16版本以上'
        } else {
            result.code = 404
            result.msg = '不存在硬盘资源，您用了网络图片'
        }
    }
    res.send(JSON.stringify(result))
})

module.exports = router
